package com.mastercard.assets.web.forms.process;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.mastercard.assets.MasterCardException;
import com.mastercard.assets.flows.FlowUtil;
import com.mastercard.assets.flows.process.FlowProcessContext;
import com.mastercard.assets.flows.process.FlowProcessInit;
import com.mastercard.assets.flows.process.FlowProcessPost;
import com.mastercard.assets.flows.process.FlowProcessPrevious;
import com.mastercard.assets.flows.process.FlowProcessResult;
import com.mastercard.assets.flows.to.FlowDataTO;
import com.mastercard.assets.flows.to.FlowImplementationTO;
import com.mastercard.assets.flows.to.FlowPreimplementationTO;
import com.mastercard.assets.jpa.TblAsset;
import com.mastercard.assets.jpa.TblFlujo;
import com.mastercard.assets.jpa.TblForma;
import com.mastercard.assets.jpa.TblPreimplementacion;
import com.mastercard.assets.jpa.TblTarea;
import com.mastercard.assets.jpa.TblTareaPreimplementacion;
import com.mastercard.assets.util.MCUtil;
import com.mastercard.assets.util.dao.MasterCardDAO;
import com.mastercard.assets.web.struts.forms.FlowProcessForm;
import com.mastercard.assets.web.util.to.UserLogin;

public class PreimplementationPricesRequestFIFormProcess
	implements
		FlowProcessInit , 
		FlowProcessPrevious , 
		FlowProcessPost
{
	public FlowProcessResult loadFormData( FlowProcessContext ctx )
		throws
			MasterCardException
	{
		System.out.println( "PreimplementationPricesRequestFIFormProcess.java: inicio" ) ;
		
		TblTareaPreimplementacion tblTareaPreimplementacion = ctx.getTblTareaPreimplementacion( ) ;
		
		System.out.println( "PreimplementationPricesRequestFIFormProcess.java: tareaPreimplemnetacion/" + tblTareaPreimplementacion.getCveTareaPreimplementacion( ) ) ;
		System.out.println( "PreimplementationPricesRequestFIFormProcess.java: tareaPreimplemnetacion.asset/" + tblTareaPreimplementacion.getTblAsset( ).getCveAsset( ) ) ;
		
		TblPreimplementacion tblPreimplementacion = tblTareaPreimplementacion.getTblPreimplementacion( ) ;
		
		System.out.println( "PreimplementationPricesRequestFIFormProcess.java: preimplemnetacion/" + tblPreimplementacion.getCvePreimplementacion( ) ) ;
		System.out.println( "PreimplementationPricesRequestFIFormProcess.java: preimplemnetacion.assets/" + tblPreimplementacion.getTblAssets( ).size( ) ) ;
		
		TblFlujo tblFlujo = tblPreimplementacion.getTblFlujo( ) ;
		
		System.out.println( "PreimplementationPricesRequestFIFormProcess.java: flujo/" + tblFlujo.getCveFlujo( ) ) ;
		
		FlowImplementationTO to = new FlowImplementationTO( ) ;
		
		to.setCveFlow( tblFlujo.getCveFlujo( ) ) ;
		to.setFlow( tblFlujo ) ;
		to.setTblTareaPreimplementacion( tblTareaPreimplementacion ) ;
		
		// extrae la tarea
		TblTarea tarea = tblTareaPreimplementacion.getTblTarea( ) ;
		
		// extrae la forma
		TblForma forma = tarea.getTblForma( ) ;
		
		System.out.println( "PreimplementationPricesRequestFIFormProcess.java: forma/" + forma.getCveForma( ) ) ;
		
		// nombre del jsp
		String jspName = forma.getArchivoForma( ) ;
		// ruta completa del jsp
		URL ruta = null ;
		try
		{
			System.out.println( "@@@@@@@@@@@@@@@@@@@" + MCUtil.getFormsDirToDisplay( ) + System.getProperty( "file.separator" ) + jspName ) ;
			ruta = new URL( "file" , "localhost" , MCUtil.getFormsDirToDisplay( ) + System.getProperty( "file.separator" ) + jspName ) ;
			
			System.out.println( "@@@@@@@@@@@@@@@@@@@" + ruta ) ;
		}catch( Exception e )
		{
			e.printStackTrace( ) ;
			
			return new FlowProcessResult( FlowUtil.FLOW_CONSTANTS_FORM_PROCESS_DATA_PROCESS_ERROR_OBTAINING_PATH , MCUtil.messages.getString( "com.mastercard.assets.web.errors.modules.flows.display.WorkFlowWorkFormErrorProcessingData.preimplementacion.ErrorCalculatingPath" , e.getMessage( ) ) , e ) ;
		}
		
//		String jspPath = ruta.getQuery( ) ;
		String jspPath = "/WEB-INF/formas/" + jspName ;
		
		System.out.println( "PreimplementationPricesRequestFIFormProcess.java: jspPath/" + jspPath ) ;
		
		java.util.List< TblAsset > assets = new ArrayList< TblAsset >( ) ;
		java.util.List< TblAsset > assetsDelFlujo = tblPreimplementacion.getTblAssets( ) ;
		
		// recorre assets
		for( TblAsset asset : assetsDelFlujo )
			// en caso de que este activo
			if( asset.getStatus( ) == 1 )
				assets.add( asset ) ;
		
		// coloca en el to
		to.setAssets( assets ) ;
		
		System.out.println( "PreimplementationPricesRequestFIFormProcess.java: assets/" + assets.size( ) ) ;
		
		// coloca los servicios
		to.setServices( MasterCardDAO.getAllActiveServices( ) ) ;
		
		System.out.println( "PreimplementationPricesRequestFIFormProcess.java: services/" + to.getServices( ).size( ) ) ;
		
		// abre el archivo
		File dir = new File( MCUtil.getFormsDir( ) ) ;
//		System.out.println( "***********" + dir.getAbsolutePath( ) ) ;
		File f = new File( dir , jspName ) ;
//		System.out.println( "***********" + f.getAbsolutePath( ) ) ;
		
//		System.getProperties( ).list( System.out ) ;
		
		String fileCode = "" ;
		StringBuffer sb = new StringBuffer( ) ;
		
		try
		{
			System.out.println( "PreimplementationPricesRequestFormProcess.java: lecturaJSP/" ) ;
			BufferedReader rIn = new BufferedReader( new FileReader( f ) ) ;
			
			System.out.println( "PreimplementationPricesRequestFormProcess.java: lecturaJSP/1" ) ;
			String line = "" ;
			
			System.out.println( "PreimplementationPricesRequestFormProcess.java: lecturaJSP/2" ) ;
			while( ( line = rIn.readLine( ) ) != null )
				sb.append( line ) ;
			
			System.out.println( "PreimplementationPricesRequestFormProcess.java: lecturaJSP/3" ) ;
			rIn.close( ) ;
			
			System.out.println( "PreimplementationPricesRequestFormProcess.java: lecturaJSP/4" ) ;
		}catch( Exception e )
		{
			e.printStackTrace( ) ;
			MasterCardDAO.closeEntityManager( ) ;
			return new FlowProcessResult( FlowUtil.FLOW_CONSTANTS_FORM_PROCESS_DATA_PROCESS_NO_FORM_FILE_EXIST , MCUtil.messages.getString( "com.mastercard.assets.web.errors.modules.flows.display.WorkFlowWorkFormErrorProcessingData.preimplementacion.NoFormFileExist" , jspName ) , e ) ;
		}
		
		// coloca la ruta del jsp
		to.setJspPath( jspPath ) ;
		to.setJspCode( sb.toString( ) ) ;
		
		sb.setLength( 0 ) ;
		sb = null ;
		
		System.out.println( "PreimplementationPricesRequestFIFormProcess.java: to/" + to.getClass( ).getCanonicalName( ) ) ;
		
                MasterCardDAO.closeEntityManager( ) ;
		return new FlowProcessResult( FlowUtil.FLOW_CONSTANTS_FORM_PROCESS_CAN_DISPLAY , to ) ;
	}
	
	public FlowProcessResult canDisplay( FlowProcessContext ctx )
	{
		TblTareaPreimplementacion tblTareaPreimplementacion = ctx.getTblTareaPreimplementacion( ) ;
		
		// en caso de uqe ya este ejecutado
		if( tblTareaPreimplementacion.getEjecutado( ) == 1 )
			return new FlowProcessResult( FlowUtil.FLOW_CONSTANTS_FORM_PROCESS_WORK_FLOW_EXECUTED ) ;
		
		// toma las clases para procesar la forma antes de desplegarla
		// toma la tarea
		TblTarea tarea = tblTareaPreimplementacion.getTblTarea( ) ;
		
		String nombreTarea = tarea.getNombre( ) ;
		
		// en caso de que la tarea haya sido desactivada
		if( tarea.getStatus( ) == 0 )
			return new FlowProcessResult( FlowUtil.FLOW_CONSTANTS_FORM_PROCESS_WORK_FLOW_WORK_DESACTIVATED ) ;
		
		// toma la forma a la que esta ligada la tarea
		TblForma forma = tarea.getTblForma( ) ;
		
		// en caso de que la forma este desactivada
		if( forma.getStatus( ) == 0 )
			return new FlowProcessResult( FlowUtil.FLOW_CONSTANTS_FORM_PROCESS_WORK_FLOW_WORK_FORM_DESACTIVATED ) ;
		
		/// se pueden agregar mas filtros
		
		return new FlowProcessResult( FlowUtil.FLOW_CONSTANTS_FORM_PROCESS_CAN_DISPLAY ) ;
	}
	
	public FlowProcessResult processExit( FlowProcessContext ctx )
		throws
			MasterCardException
	{
		int stepupResult = -1 ;
		
		HttpServletRequest request = ctx.getRequest( ) ;
		
		String comentarios = request.getParameter( "comentarios" ) ;
		
		String[ ] selectServices = request.getParameterValues( "selectService" ) ;
		
		System.out.println( "PreimplementationPricesRequestFormProcess.java: selectServices/" + selectServices ) ;
		System.out.println( "PreimplementationPricesRequestFormProcess.java: selectServices/" + ( selectServices == null ? 0 : selectServices.length ) ) ;
		
		if( selectServices == null || selectServices.length == 0 )
			return new FlowProcessResult( FlowUtil.FLOW_CONSTANTS_FORM_PROCESS_DATA_PROCESS_ERROR_RELOAD , MCUtil.messages.getString( "com.mastercard.assets.web.errors.modules.flows.display.WorkFlowWorkFormErrorProcessingData.preimplementacion.NoServicesSelected" ) , null ) ;
		
		String[ ] comentario = new String[ selectServices.length ] ;
		int[ ] servicios = new int[ selectServices.length ] ;
		
		StringBuffer sb = new StringBuffer( ) ;
		
		for( int index = 0 ; index < selectServices.length ; index++ )
		{
			String service = selectServices[ index ] ;
			
			String comentarioService = request.getParameter( "comentario-" + service ) ;
			
			comentario[ index ] = comentarioService ;
			
			try
			{
				servicios[ index ] = Integer.parseInt( service ) ;
			}catch( Exception e )
			{
				sb.append( MCUtil.messages.getString( "com.mastercard.assets.web.errors.modules.flows.display.WorkFlowWorkFormErrorProcessingData.preimplementacion.WrongNumber" , service ) + "\n" ) ;
			}
		}
		
		if( sb.length( ) > 0 )
		{
			String error = sb.toString( ) ;
			
			sb.setLength( 0 ) ;
			
			return new FlowProcessResult( FlowUtil.FLOW_CONSTANTS_FORM_PROCESS_DATA_PROCESS_ERROR_RELOAD , error , null ) ;
		}
		
		// procesa los datos
		// los guarda en BD
		try
		{
			stepupResult = MasterCardDAO.processCotizaServicioFormOne( ctx.getUser( ) , servicios , comentario , comentarios , ctx.getTblTareaPreimplementacion( ) , ctx.getForm( ).getExit( ) ) ;
		}catch( Exception e )
		{
                    MasterCardDAO.closeEntityManager( ) ;
			return new FlowProcessResult( FlowUtil.FLOW_CONSTANTS_FORM_PROCESS_DATA_PROCESS_ERROR_RELOAD , e.getMessage( ) , e ) ;
		}
		
                MasterCardDAO.closeEntityManager( ) ;
		return new FlowProcessResult( FlowUtil.FLOW_CONSTANTS_FORM_PROCESS_DATA_PROCESS_SUCCESS , stepupResult ) ;
	}
}
